package com.konsung.ksdc.manager.community;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.mqtt.MqttNoticeConstant;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.config.NetConfig;
import com.squareup.picasso.Picasso;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;

/**
 * 康尚百科列表页
 * Created by andy on 2017/3/13.
 */

public class KonsungWikiActivity extends Activity {
    @Bind(R.id.ll_wiki_container)
    LinearLayout llWikiContainer;
    @Bind(R.id.sv_wiki_container)
    ScrollView svWikiContainer;
    @Bind(R.id.ptr_wiki_resflsh)
    protected PtrFrameLayout ptrFrameLayout; //刷新控件
    @Bind(R.id.iv_back)
    ImageView ivBack;
    private int searchIndex; // 分页页码
    private int insertIndex = 0; // 消息区插入位置
    public static final long PAGE_SIZE = 3L;
    private String newestMsg; // 最新的推送消息标题

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_konsung_wiki);
        ButterKnife.bind(this);
        initHistoryMsg();
        initEvent();
        updateNoticeReadState();
    }

    /**
     * 初始化
     */
    private void initEvent() {
        /**
         * 谷歌刷新风格
         */
        final MaterialHeader header = new MaterialHeader(this);
        header.setBackgroundResource(R.color.refresh_bg);
        int[] colors = getResources().getIntArray(R.array.google_colors);
        header.setColorSchemeColors(colors);
        header.setPadding(0, DensityUtils.dp2px(this, 15), 0, 0);
        header.setPtrFrameLayout(ptrFrameLayout);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(new PtrHandler() {

            //需要加载数据时触发
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptrFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //刷新数据
                        loadMsgData();
                        svWikiContainer.post(new Runnable() {
                            @Override
                            public void run() {
                                svWikiContainer.scrollTo(0, svWikiContainer.getTop());
                            }
                        });
                    }
                }, 1800);
            }

            /**
             * 检查是否可以执行下来刷新，比如列表为空或者列表第一项在最上面时。
             */
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 加载聊天记录
     */
    private void loadMsgData() {
        // 开始处理每一条消息记录
        List<MqttMsgBean> historyMsgs = fetchMqttMessages(searchIndex);
        if (historyMsgs.isEmpty()) {
            //刷新停止
            ptrFrameLayout.refreshComplete();
            return;
        }
        ptrFrameLayout.refreshComplete();
        Collections.reverse(historyMsgs);

        // 叠加页码
        searchIndex++;

        insertIndex = 0;
        for (int i = 0; i < historyMsgs.size(); i++) {
            MqttMsgBean bean = historyMsgs.get(i);
            //拦截注册前的消息
            if (DateUtils.compareMsgTime(DateUtils.convertTimeToLong(bean.getMsgSendDate()))) {
                continue;
            }
//            LogUtils.e("loadMsgData", bean.toString());
            long time = 0;
            try {
                time = DateUtils.getDateFormat(bean.getMsgSendDate(),
                        DateUtils.yyyyMMddHHmmss).getTime();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 添加时间线
            addTimeLine(time, insertIndex);

            addMsgView(bean, insertIndex);
        }
    }

    /**
     * 初始化历史消息，默认加载最新的10条
     */
    private void initHistoryMsg() {
        // 开始处理每一条消息记录
        List<MqttMsgBean> historyMsgs = fetchMqttMessages(0);
        if (historyMsgs.isEmpty()) {
            newestMsg = "";
            return;
        }
        searchIndex++; // 叠加页码

        Collections.reverse(historyMsgs);

        for (MqttMsgBean bean : historyMsgs) {
            //拦截注册前的消息
            if (DateUtils.compareMsgTime(DateUtils.convertTimeToLong(bean.getMsgSendDate()))) {
                continue;
            }
            long time = 0;
            try {
                time = DateUtils.getDateFormat(bean.getMsgSendDate(),
                        DateUtils.yyyyMMddHHmmss).getTime();
            } catch (Exception e) {
                e.printStackTrace();
            }

            addTimeLine(time);

            addMsgView(bean);
        }
        newestMsg = historyMsgs.get(historyMsgs.size() - 1).getMsgContent().split("#")[0];
    }

    /**
     * 添加WIKI消息到消息区
     * 数据包分为4段，使用#号分隔，
     * 第一段为消息标题，第二段为图片地址，第三段为消息URL，第四段为消息描述
     * @param mqttMsg 消息
     * @param index 索引
     */
    private void addMsgView(final MqttMsgBean mqttMsg, int index) {
        View view = getLayoutInflater().inflate(R.layout
                .item_konsung_wiki, null);
        final String[] msgBody = mqttMsg.getMsgContent().split("ks_split");
        //如果推送的消息长度不合符规范
        if (msgBody.length != 4) {
            return;
        }

        TextView tvMsgTile = (TextView) view.findViewById(R.id.tv_msg_title);
        ImageView ivMsgPic = (ImageView) view.findViewById(R.id.iv_msg_pic);
        TextView tvMsgContent = (TextView) view.findViewById(R.id.tv_msg_content);
        final RelativeLayout rlSelected = (RelativeLayout) view.findViewById(R.id.rl_selected);
        Button btnDelete = (Button) view.findViewById(R.id.btn_delete);

        // 消息标题
        tvMsgTile.setText(msgBody[0]);
        // 图片：一个http协议的URL
        String picUrl = StringUtils.appendPicPath(msgBody[1]);

        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(ivMsgPic);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWikiWebView(msgBody[3]);
            }
        });
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                rlSelected.setVisibility(View.VISIBLE);
                return true;
            }
        });
        rlSelected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlSelected.setVisibility(View.GONE);
            }
        });
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RuntimeExceptionDao dao = DatabaseHelper.getHelper(KonsungWikiActivity.this)
                        .getRuntimeExceptionDao(MqttMsgBean.class);
                dao.delete(mqttMsg);
                llWikiContainer.removeAllViews();
                initHistoryMsg();
                updateNotice();
            }
        });
        // 消息描述
        tvMsgContent.setText(msgBody[2]);

        // 将消息添加到消息区
        llWikiContainer.addView(view, index);
        insertIndex++;
    }

    /**
     * 更新消息提醒界面数据
     */
    private void updateNotice() {
        RuntimeExceptionDao noticeDao = DatabaseHelper.getHelper(KonsungWikiActivity.this)
                .getRuntimeExceptionDao(MqttMsgNotice.class);
        List<MqttMsgNotice> list = noticeDao.queryForEq("noticeType", MqttNoticeConstant
                .NOTICE_TYPE_WIKI);
        if (null != list && list.size() > 0) {
            list.get(0).setNoticeMsg(newestMsg);
            noticeDao.update(list.get(0));
        }
    }

    /**
     * 打开百科网页浏览器
     * @param url 地址
     */
    private void openWikiWebView(String url) {
        if (!url.contains(NetConfig.PROTOCOL_SCHAME)) {
            url = NetConfig.getImPushUrl(url);
        }
        Intent intent = new Intent(this, SimpleWebViewActivity.class);
        intent.putExtra(SimpleWebViewActivity.PARAMS_URL, url);
        startActivity(intent);
    }

    /**
     * 添加当前用户消息到消息区底部
     * @param mqttMsg 消息
     */
    private void addMsgView(MqttMsgBean mqttMsg) {
        addMsgView(mqttMsg, -1);
        scrollMsgAreaFocusDown();
    }

    /**
     * 滑动消息区到底部
     */
    private void scrollMsgAreaFocusDown() {
        // 滚动到消息区底部
        svWikiContainer.post(new Runnable() {
            @Override
            public void run() {
                svWikiContainer.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    /**
     * 分页查询消息记录，取最新记录
     * @param index 索引
     * @return 数据
     */
    private List<MqttMsgBean> fetchMqttMessages(int index) {

        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(MqttMsgBean.class);
        QueryBuilder qb = dao.queryBuilder();
        try {
            qb.where().eq("ownerUserId", NetConfig.currentUser.getUserId())
                    .and()
                    .eq("msgType", MqttMsgUtils.MSG_TYPE_WIKI);
            qb.orderBy("msgId", false);
            qb.limit(PAGE_SIZE);
            qb.offset(PAGE_SIZE * index);

            // 开始处理每一条消息记录
            return qb.query();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ArrayList<MqttMsgBean>();
    }

    /**
     * 添加时间线到消息区底部
     * @param current 当前
     */
    private void addTimeLine(long current) {
        addTimeLine(current, -1);
    }

    /**
     * 添加时间线
     * @param current 当前
     * @param index 索引
     */
    private void addTimeLine(long current, int index) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");

        LinearLayout.LayoutParams params = new LinearLayout
                .LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 60);
        params.gravity = Gravity.CENTER;
        params.topMargin = 50;
        params.bottomMargin = 20;

        TextView txtTimeLine = new TextView(this);
        txtTimeLine.setBackgroundResource(R.drawable.bg_grey_round);
        txtTimeLine.setLayoutParams(params);
        txtTimeLine.setPadding(20, 0, 20, 0);
        txtTimeLine.setGravity(Gravity.CENTER);
        txtTimeLine.setTextSize(11);
        txtTimeLine.setTextColor(getResources().getColor(R.color.bg_normal));
        txtTimeLine.setText(sdf.format(current));

        llWikiContainer.addView(txtTimeLine, index);
        insertIndex++;
    }

    /**
     * 更新消息收取状态
     */
    private void updateNoticeReadState() {
        // 标记消息提醒已读
        RuntimeExceptionDao noticeDao = DatabaseHelper.getHelper(this)
                .getRuntimeExceptionDao(MqttMsgNotice.class);
        UpdateBuilder ub = noticeDao.updateBuilder();
        try {
            ub.where().eq("noticeType", MqttNoticeConstant.NOTICE_TYPE_WIKI)
                    .and()
                    .eq("ownerUserId", NetConfig.currentUser.getUserId());
            ub.updateColumnValue("isRead", "Y");
            ub.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
